import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/apartment/room_detail/widgets/check_in_record/index.dart";
import "package:ct_pa_majordomo/pages/apartment/room_detail/widgets/unlock_record/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/detail/widgets/rent_info/index.dart";
import "package:ct_pa_majordomo/pages/transfer_station.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/info_block/info_block.dart";
import "package:ct_pa_majordomo/widgets/info_block/info_item.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class RoomDetail extends StatefulWidget {
  final Map? info;
  final Map room;
  const RoomDetail({super.key, this.info, required this.room});

  @override
  State<StatefulWidget> createState() => _RoomDetailState();

}

class _RoomDetailState extends State<RoomDetail> {
  Map? _info;
  Map? _room;

  final Map _rentTypeDict = {
    1: "每1月",
    2: "每2月",
    3: "每3月",
    4: "每4月",
    5: "每半年",
    6: "每一年",
    7: "一次性",
  };
  List _operationList = [];

  String _rentTypeValue () {
    if (Utils.isEmpty(_info?["rentObject"]) || _info?["rentObject"]?["rentType"] == -1) {
      return "--";
    }
    return _rentTypeDict[_info?["rentObject"]?["rentType"]];
  }

  Widget _textButton({
    GestureTapCallback? onTap,
   required String text,
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Text(text, textAlign: TextAlign.right, style: const TextStyle(color: ThemeVars.colorPrimary),),
    );
  }

  Future<void> _updateRoomInfo({required Map<String, dynamic> params }) async {
    await apartmentApi.updateRoomInfo(params);
    EasyLoading.showToast("修改成功");
  }

  void _getCheckInInfo() async {
    Map resData = await checkInApi.getCheckInInfo(checkInId: _info?["checkInId"]);
    Map data = resData["data"];
    setState(() {
      _info = data;
      _room = data["room"];
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    setState(() {
      _info = widget.info;
      _room = widget.room;
    });
    _operationList = [{
      "name": "开门记录",
      "path": Keys.APARTMENT_UNLOCK_RECORD,
      "arguments": widget.room["roomId"],
      "icon": Icon(Icons.door_back_door_outlined, color: ThemeVars.colorPrimary,)
    }, {
      "name": "入住记录",
      "path": Keys.APARTMENT_CHECK_IN_RECORD,
      "arguments": widget.room["roomId"],
      "icon": Icon(Icons.fiber_smart_record_outlined, color: ThemeVars.colorPrimary,)
    }];
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      _info = widget.info;
      _room = widget.room;
    });
    _operationList = [{
      "name": "开门记录",
      "path": Keys.APARTMENT_UNLOCK_RECORD,
      "arguments": widget.room["roomId"],
      "icon": Icon(Icons.door_back_door_outlined, color: ThemeVars.colorPrimary,)
    }, {
      "name": "入住记录",
      "path": Keys.APARTMENT_CHECK_IN_RECORD,
      "arguments": widget.room["roomId"],
      "icon": Icon(Icons.fiber_smart_record_outlined, color: ThemeVars.colorPrimary,)
    }];
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "房间详情",
      child: ListView(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(_operationList.length, (index) {
                return GestureDetector(
                  onTap: () {
                    Stacker.pushNamed(_operationList[index]["path"], arguments: _operationList[index]["arguments"]);
                  },
                  child: Column(
                    children: [
                      _operationList[index]["icon"],
                      SizedBox(height: 5,),
                      Text(_operationList[index]["name"]),
                    ],
                  ),
                );
              })
            ),
          ),
          SizedBox(height: 12,),
          InfoBlock(
            title: "${_room?["buildingName"]}${_room?["roomName"]}",
            actions: [
              _textButton(
                text: "编辑",
                onTap: () {
                  taiDialog(
                    context: context,
                    title: "编辑房号",
                    child: Column(
                      children: [
                        Text("${_room?["buildingName"]}${_room?["roomName"]}"),
                        SizedBox(height: 8,),
                        TextFormField(
                          autofocus: true,
                          textAlign: TextAlign.center,
                          decoration: const InputDecoration(
                            hintText: "请输入",
                            hintStyle: TextStyle(color: ThemeVars.colorTextTer),
                            border: InputBorder.none,
                            filled: true,
                            fillColor: ThemeVars.colorBackground,
                          ),
                          initialValue: _room?["roomName"],
                          onChanged: (val) {
                            setState(() {
                              _room?["roomName"] = val;
                            });
                          },
                        ),
                      ],
                    ),
                    onConfirm: (taiContext) async {
                      Map<String, dynamic> params = {
                        "roomId": _room?["roomId"],
                        "name": _room?["roomName"],
                      };
                      _updateRoomInfo(params: params);
                      if (taiContext.mounted) {
                        Navigator.of(taiContext).pop();
                      }
                    }
                  );
                }
              )
            ],
          ),
          
          if (_info?["checkInId"] != null) 
          ...[
            SizedBox(height: 12,),
            InfoBlock(
              title: "房租信息",
              actions: [
                _textButton(
                  text: "编辑",
                  onTap: () {
                    Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                      return RentInfo(
                        checkInId: _info?["checkInId"],
                        rentObject: _info?["rentObject"],
                        changeInfo: () {
                          _getCheckInInfo();
                        },
                      );
                    },),);
                  }
                )
              ],
              children: Utils.isNotEmpty(_info?["rentObject"]) ? [
                InfoItem(label: "月租金", value: "${_info?["rentObject"]?["rent"] ?? "--"}"),
                InfoItem(label: "押金", value: "${_info?["rentObject"]?["deposit"] ?? "--"}"),
                InfoItem(label: "付款方式", value: _rentTypeValue() ),
              ] : [],
            ),
          ],
          SizedBox(height: 12,),
          InfoBlock(
            title: "备注",
            actions: [
              _textButton(
                text: "编辑",
                onTap: () {
                  Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                    return EditRemark(remark: _room?["remark"] ?? "");
                  },),).then((value) async {
                    if (value != null) {
                      Map<String, dynamic> params = {
                        "roomId": _room?["roomId"],
                        "remark": value,
                      };
                      await _updateRoomInfo(params: params);
                      _getCheckInInfo();
                    }
                  });
                }
              ),
            ],
            content: Utils.isNotEmpty(_room?["remark"]) ? Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(3)),
                color: ThemeVars.colorBackground,
              ),
              child: Text(_room?["remark"] ?? "", textAlign: TextAlign.left,),
            ) : null,
          ),
          Padding(
            padding: EdgeInsets.all(ThemeVars.paddingPage),
            child: _textButton(
              text: "删除房间",
              onTap: () {
                taiDialog(
                  context: context,
                  child: const Text("确定删除房间？", textAlign: TextAlign.center,),
                  onConfirm: (taiContext) async {
                    await apartmentApi.removeRoom(roomIds: _room!["roomId"].toString());
                    EasyLoading.showToast("删除成功");
                    Stacker.pushNamedAndRemoveUntil(Keys.MAIN, null, arguments: {"index": 1});
                  }
                );
              }
            )
          )
        ],
      ),
    );
  }

}